package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrdersTask {

    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ? ") //每分钟检查一次
    public void processTimeoutOrder(){
        log.info("定时处理超时订单"+ LocalDateTime.now());
        List<Orders> ordersList = orderMapper.checkOutTimeOrders();
        if(ordersList != null && !ordersList.isEmpty()){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("用户未支付超时，订单取消");
                orderMapper.update(orders);
            });
        }
    }

    @Scheduled(cron = "0 0 1 * * ? ") //每天凌晨一点检查一次
    public void processDeliveryOrder(){
        log.info("定时处理未完成订单"+ LocalDateTime.now());
        List<Orders> ordersList = orderMapper.checkDeliveryOrder();
        if(ordersList != null && !ordersList.isEmpty()){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            });
        }
    }

}
